using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;

namespace FileManager.Services
{
    public static class WeChatImageDecryptor
    {
        // 微信图片文件头特征
        private static readonly byte[] WECHAT_IMAGE_HEADER = { 0xFF, 0xD8, 0xFF, 0xE0 };

        public static bool IsWeChatEncryptedImage(string filePath)
        {
            try
            {
                using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] header = new byte[4];
                fs.Read(header, 0, 4);
                return !header.SequenceEqual(WECHAT_IMAGE_HEADER);
            }
            catch
            {
                return false;
            }
        }

        public static Stream DecryptImage(string filePath)
        {
            try
            {
                byte[] encryptedData = File.ReadAllBytes(filePath);
                byte[] decryptedData = new byte[encryptedData.Length];
                
                // 微信图片简单异或加密（0xFF）
                for (int i = 0; i < encryptedData.Length; i++)
                {
                    decryptedData[i] = (byte)(encryptedData[i] ^ 0xFF);
                }

                return new MemoryStream(decryptedData);
            }
            catch
            {
                return null;
            }
        }
    }
}